// 新生专区模块
const Controller = require('egg').Controller;
const sqlConfig = require('../util/sqlConfig')
const err = require('../util/err')
const moment = require('moment')
const util = require('../util/util')
const axios = require('axios')
const parser = require("fast-xml-parser");  // join to xml
let j2xParser = parser.j2xParser
const X2JS = require('node-x2js');
const md5 = require('md5')
const qr = require('qr-image')
const appid = 'wx069bb9fd47eb702b'      // 小程序ID
const mch_id = '1605857462'             //商户号id
const appSecret = '9bb97baab7f3e893645262f0e5344a9b'    //小程序appSecret
const WX_SHOP_KEY = 'liuhu666liuhu666liuhu666liuhu666'  //商户平台设置的密钥key
// https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1     微信支付文档

class NewStudent extends Controller {
    // 新生专区类型列表
    async nsTypeList() {
        const { ctx, app } = this;
        const { mysql } = app
        const r_body = ctx.request.body;
        const { uSchoolId } = r_body
        const data = await mysql.select('nsType', {
            where: {
                uSchoolId
            }
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: data
        }
    }
    // 新生专区列表
    async nsBusinessList() {
        const { ctx, app } = this;
        const { mysql } = app
        const r_body = ctx.request.body;
        const { uSchoolId } = r_body
        const data = await mysql.select('nsBusiness', {
            where: {
                uSchoolId,
                isGrounding: 1
            },
            orders: [['ord', 'desc']],
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: data
        }
    }
    // 新生专区列表--后台
    async nsBusinessManageList() {
        const { ctx, app } = this;
        const { mysql } = app
        const r_body = ctx.request.body;
        const { uSchoolId } = r_body
        const data = await mysql.select('nsBusiness', {
            where: {
                uSchoolId,
            }
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: data
        }
    }
    // 新生专区新增
    async nsBusinessAdd() {
        const { ctx, app } = this;
        const { mysql } = app
        let { body } = ctx.request;
        delete body.groundTime

        await mysql.insert('nsBusiness', {
            ...body,
            groundTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }
    // 新生专区列修改
    async nsBusinessEdit() {
        const { ctx, app } = this;
        const { mysql } = app
        let { body } = ctx.request;
        const { id } = body
        delete body.id
        await mysql.update('nsBusiness', body, {
            where: {
                id
            }
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }

    // 新生专区详情
    async nsBusinessDetail() {
        const { ctx, app } = this;
        const { mysql } = app
        const r_body = ctx.request.body;
        const { id } = r_body
        const data = await mysql.select('nsBusiness', {
            where: {
                id
            }
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: data.length ? data[0] : {}
        }
    }

    // 电话卡介绍
    async nsTelText() {
        const { ctx, app } = this;
        const { mysql } = app
        const r_body = ctx.request.body;
        const { uSchoolId } = r_body
        const data = await mysql.select('nsTelText', {
            where: {
                uSchoolId,
                isGrounding: 1
            }
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: data
        }
    }

    // 用户下单
    async nsAddOrder() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        if (r_body) {
            const { loginManageId, uSchoolId, nsTypeId, nsBusinessId, name, studentNum, telInput, height, weight, size, tel, telType, price, telWX, openid, schoolType, postage, idCard, loginId } = r_body
            const arrBus = await mysql.select('nsBusiness', {
                where: { id: nsBusinessId }
            })
            // 学校不匹配
            if (arrBus[0].uSchoolId !== uSchoolId) {
                ctx.body = err.err14
            } else {
                let choiceArr = []
                if (tel) {
                    choiceArr = await mysql.select('nsTel', {
                        where: { tel }
                    })
                }

                const telExit = choiceArr.length ? choiceArr[0].choice === 1 : true   // 该号码未被选中   choice是否选中 1 否 2 是 
                if (!telExit) {
                    ctx.body = {
                        code: 200,
                        msg: '-1',
                        data: {}
                    }
                } else {
                    const orderNum = `zn${new Date().getTime()}ns${uSchoolId}`  //  15位时间戳
                    const params2 = {
                        appid,
                        mch_id,
                        nonce_str: util.makeCode(30),
                        body: '新生专区支付',
                        out_trade_no: orderNum,
                        total_fee: parseInt((price * 100).toFixed(0)),
                        spbill_create_ip: '139.155.230.209',
                        notify_url: 'https://api.zhongningwenhua.com/notifyUrl',
                        trade_type: 'JSAPI',
                        openid,
                        profit_sharing: 'N',     // 是否分账
                    }
                    let str = util.getWXSing(params2, WX_SHOP_KEY)
                    params2.sign = str
                    const j2xparser = new j2xParser();
                    let obj = {
                        xml: params2
                    }
                    const xml = j2xparser.parse(obj)
                    let prepay_id = ''
                    await axios.post('https://api.mch.weixin.qq.com/pay/unifiedorder', xml, {
                        headers: {
                            "Content-Type": "application/xml"
                        },
                    }).then(function (res) {
                        const rData = parser.parse(res.data)
                        prepay_id = 'prepay_id=' + rData.xml.prepay_id
                    }).catch(function (error) {
                        ctx.body = err.err3(error)
                    })
                    const params = {
                        loginManageId, uSchoolId, nsTypeId, nsBusinessId, name, studentNum, telInput, height, weight, size, tel, telType, price, prepay_id,
                        nsOrderTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'), telWX, openid, orderNum, schoolType, postage, idCard, loginId
                    }
                    await mysql.insert('nsOrder', params)
                    ctx.body = {
                        code: 200,
                        msg: '下单成功',
                        data: {
                            prepay_id
                        }
                    }
                }
            }

        } else {
            ctx.body = err.err1
        }
    }
    // 支付
    async nsPay() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { uSchoolId, nsOrderId, nsBusinessId, tel, postage, name, studentNum, idCard, telInput, telWX } = r_body
        const { mysql } = app
        if (r_body) {
            const ticketCode = `${util.makeCode(12)}ns${uSchoolId}`
            await mysql.update('nsOrder', {
                ticketCode,
                status: 2,
                idCard,
            }, {
                where: {
                    id: nsOrderId
                }
            })
            const _data = await mysql.select('nsBusiness', {
                where: {
                    id: nsBusinessId
                }
            })
            const num = parseInt(_data[0].num + 1)
            await mysql.update('nsBusiness', {
                num,
            }, {
                where: {
                    id: nsBusinessId
                }
            })

            // 选择号码存在，写入nsTel表
            if (tel) {
                await mysql.update('nsTel', {
                    postage,
                    choice: 2,
                    name,
                    studentNum,
                    idCard,
                    telInput,
                    telWX
                }, {
                    where: {
                        tel
                    }
                })
            }
            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: {}
            }
        } else {
            ctx.body = err.err1
        }
    }

    // 根据prepay_id查询订单详情
    async nsOrderPrepay() {
        const { ctx, app } = this;
        const { mysql } = app
        const r_body = ctx.request.body;
        const { prepay_id } = r_body
        const data = await mysql.select('nsOrder', {
            where: {
                prepay_id
            }
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: data.length ? data[0] : {}
        }
    }

    // 删除订单
    async nsDeleteOrder() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { nsOrderId } = r_body
        const { mysql } = app
        if (r_body && nsOrderId > 0) {
            await mysql.delete('nsOrder', {
                id: nsOrderId
            });
            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: {}
            }
        } else {
            ctx.body = err.err1
        }
    }

    //  新生专区电话号码模糊搜索  
    async nsTelList() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const list = await mysql.query(sqlConfig.nsTelList(r_body))
        list.map((item, i) => {
            item.key = i
        })
        const total = util.handelData(await mysql.query(sqlConfig.nsTelTotal(r_body)))[0]['count(*)']
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {
                list,
                total
            }
        }
    }

    // 小程序端--订单列表
    async nsOrderList() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { loginId, status, uSchoolId } = r_body
        const { mysql } = app
        if (r_body) {
            const list = await mysql.query(sqlConfig.nsOrderList(r_body))
            for (let index = 0; index < list.length; index++) {
                const element = list[index]
                let data2 = await mysql.select('nsBusiness', {
                    where: { id: element.nsBusinessId }
                })
                element.time = element.nsOrderTime
                element.nsBusinessDetail = data2[0]
            }

            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: list
            }
        } else {
            ctx.body = err.err1
        }
    }

    // h5--小程序端 查询状态
    async nsTicketStatus() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const { ticketCode } = r_body
        if (r_body) {
            const data = await mysql.select('nsOrder', {
                columns: ['status'],
                where: {
                    ticketCode
                }
            })
            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: data.length ? data[0] : {}
            }
        } else {
            ctx.body = err.err1
        }
    }

    // h5验券 
    async nsVertifyTicket() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const { ticketCode } = r_body
        if (r_body) {
            const result = await mysql.update('nsOrder', {
                status: 3
            }, {
                where: {
                    ticketCode
                }
            })
            if (result.affectedRows === 1) {
                ctx.body = {
                    code: 200,
                    msg: 'SUCCESS',
                    data: {}
                }
            } else {
                ctx.body = err.err11
            }

        } else {
            ctx.body = err.err1
        }
    }

    // 后台订单列表
    async nsOrderManageList() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const list = await mysql.query(sqlConfig.nsOrderManageList(r_body))
        for (let index = 0; index < list.length; index++) {
            const element = list[index]
            let data2 = await mysql.select('nsBusiness', {
                where: { id: element.nsBusinessId }
            })
            element.nsBusinessDetail = data2[0]
            element.nsTitle = data2[0].title
            element.key = index
        }
        const total = util.handelData(await mysql.query(sqlConfig.nsOrderManageTotal(r_body)))[0]['count(*)']
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {
                list,
                total
            }
        }
    }


    // 电话卡资费管理
    // 列表
    async nsTelTextList() {
        const { ctx, app } = this;
        const { mysql } = app
        const r_body = ctx.request.body;
        const { uSchoolId } = r_body
        const data = await mysql.select('nsTelText', {
            where: {
                uSchoolId,
            }
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: data
        }
    }
    // 编辑
    async nsTelTextEdit() {
        const { ctx, app } = this;
        const { mysql } = app
        let { body } = ctx.request;
        const { id } = body
        delete body.id
        await mysql.update('nsTelText', body, {
            where: {
                id
            }
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }
    // 新增  nsTelTextAdd
    async nsTelTextAdd() {
        const { ctx, app } = this;
        const { mysql } = app
        let { body } = ctx.request;
        await mysql.insert('nsTelText', {
            ...body
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }


    // lh直列
    async lhColumnList() {
        const { ctx, app } = this;
        const { mysql } = app
        const r_body = ctx.request.body;
        const { type, loginId } = r_body
        const data = await mysql.select('lhColumn', {
            where: {
                type,
                loginId
            }
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: data
        }
    }
    // 收支新增
    async lhPayAdd() {
        const { ctx, app } = this;
        const { mysql } = app
        let { body } = ctx.request;
        const { isPay, price, loginId } = body
        const surplus = await mysql.select('lhColumn', {
            where: {
                type: 'surplus',
                loginId
            }
        })
        const _priceAll = isPay === 1 ? parseFloat(surplus[0].value) - parseFloat(price) : parseFloat(surplus[0].value) + parseFloat(price)
        body.priceAll = _priceAll

        await mysql.update('lhColumn', {
            value: _priceAll
        }, {
            where: {
                type: 'surplus',
                loginId
            }
        })
        await mysql.insert('lhPay', {
            ...body,
            time: moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }
    // 收支编辑
    async lhPayEdit() {
        const { ctx, app } = this;
        const { mysql } = app
        let { body } = ctx.request;
        const { id } = body
        delete body.id
        await mysql.update('lhPay', body, {
            where: {
                id
            }
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }
    // 收支列表
    async lhPayList() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const list = await mysql.query(sqlConfig.lhPayList(r_body))
        const total = util.handelData(await mysql.query(sqlConfig.lhPayTotal(r_body)))[0]['count(*)']
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {
                list,
                total
            }
        }
    }
    // 收支删除
    async lhPayDelete() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { id, isPay, price,loginId } = r_body
        const { mysql } = app

        await mysql.delete('lhPay', {
            id
        });
        const surplus = await mysql.select('lhColumn', {
            where: {
                type: 'surplus',
                loginId,
            }
        })
        const _priceAll = isPay === 2 ? parseFloat(surplus[0].value) - parseFloat(price) : parseFloat(surplus[0].value) + parseFloat(price)
        await mysql.update('lhColumn', {
            value: _priceAll
        }, {
            where: {
                type: 'surplus',
                loginId
            }
        })
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {}
        }
    }

    // 收入支出统计图
    async lhSummaryChart() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const { mysql } = app
        const _data = {}
        const list = await mysql.query(sqlConfig.summaryChart(r_body))
        // 收入
        const dataIncome = list.filter(item => item.isPay === 2)
        const dataIncomeUnique = util.uniqueArray(dataIncome, 'type')
        const dataIncomeChart = []
        dataIncomeUnique.map(item1 => {
            let price = 0
            dataIncome.map(item2 => {
                if (item1.type === item2.type) {
                    price += parseFloat(item2.price)
                }
            })
            dataIncomeChart.push({
                price,
                type: item1.type
            })
        })
        // 支出
        const dataPay = list.filter(item => item.isPay === 1)
        const dataPayUnique = util.uniqueArray(dataPay, 'type')
        const dataPayChart = []
        dataPayUnique.map(item1 => {
            let price = 0
            dataPay.map(item2 => {
                if (item1.type === item2.type) {
                    price += parseFloat(item2.price)
                }
            })
            dataPayChart.push({
                price,
                type: item1.type
            })
        })

        // 收入总数
        let priceAllIncome = 0
        dataIncomeChart.map(item=>{
            priceAllIncome+= parseFloat(item.price)
        })

        // 支出总数
        let priceAllPay = 0
        dataPayChart.map(item=>{
            priceAllPay+= parseFloat(item.price)
        })

        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {
                priceAllIncome,
                priceAllPay,
                dataIncomeChart,
                dataPayChart
            }
        }
    }


    async lhTest() {
        const { ctx, app } = this;
        const { mysql } = app
        const body = ctx.request.body;
        // const data = await mysql.select('nsOrder', {})
        ctx.body = {
            code: 200,
            msg: 'SUCCESS',
            data: {
                value:'data',
                body
            }
        }
    }
}



module.exports = NewStudent;